package com.ftwj.controller.app;

import com.ftwj.dto.ApiResponse;
import com.ftwj.entity.UserAppointmentInfo;
import com.ftwj.service.UserAppointmentInfoService;
import com.ftwj.utils.result.MessageEnum;
import com.ftwj.utils.result.ResultBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import java.util.List;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/appointmentsInfo")
public class UserAppointmentInfoController {

    @Autowired
    private UserAppointmentInfoService userAppointmentInfoService;

    /**
     * 创建新的预约
     * @param userAppointmentInfo 预约信息
     * @return 操作结果
     */
    @PostMapping("/insert")
    public ResponseEntity<ApiResponse<Void>> createAppointment(
            @RequestBody UserAppointmentInfo userAppointmentInfo
    ) {
        ApiResponse<Void> response = userAppointmentInfoService.createAppointment(userAppointmentInfo);

        // 根据返回的状态码设置响应状态
        if (response.getCode() == MessageEnum.SUCCESS.getCode()) {
            return ResponseEntity.ok(response);
        } else {
            return ResponseEntity.status(response.getCode()).body(response);
        }
    }

    /**
     * 根据ID获取预约信息
     * @param id 预约ID
     * @return 预约信息
     */
    @GetMapping("/selectId/{id}")
    public ResponseEntity<UserAppointmentInfo> getAppointmentById(@PathVariable String id) {
        UserAppointmentInfo appointment = userAppointmentInfoService.getAppointmentById(id);
        if (appointment != null) {
            return ResponseEntity.ok(appointment); // 返回200状态码和预约信息
        } else {
            return ResponseEntity.notFound().build(); // 返回404状态码，表示未找到资源
        }
    }

    /**
     * 更新预约信息
     * @param userAppointmentInfo 更新后的预约信息
     * @return 操作结果
     */
    @PutMapping("/update")
    public ResponseEntity<Void> updateAppointment(@RequestBody UserAppointmentInfo userAppointmentInfo) {
        try {
            userAppointmentInfoService.updateAppointment(userAppointmentInfo);
            return ResponseEntity.ok().build(); // 返回200状态码，表示成功
        } catch (Exception e) {
            log.error("Error updating appointment: ", e);
            return ResponseEntity.status(500).build(); // 返回500状态码，表示服务器错误
        }
    }

    /**
     * 删除预约
     * @param id 预约ID
     * @return 操作结果
     */
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<ResultBean> deleteAppointment(@PathVariable String id) {
        try {
            // 调用服务层删除预约
            ResultBean result = userAppointmentInfoService.deleteAppointment(id);
            // 根据返回的code设置响应状态码
            HttpStatus status = HttpStatus.valueOf(result.getCode());
            return ResponseEntity.status(status).body(result);
        } catch (Exception e) {
            log.error("Error deleting appointment: ", e);
            // 返回500状态码和错误消息
            ResultBean result = new ResultBean(500, "Internal Server Error: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    @ExceptionHandler(ResponseStatusException.class)
    public ResponseEntity<String> handleResponseStatusException(ResponseStatusException e) {
        log.error("Response status exception: ", e);
        return ResponseEntity.status(e.getStatus()).body(e.getReason());
    }


    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception e) {
        log.error("Internal server error: ", e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An unexpected error occurred.");
    }

    /**
     * 获取所有有效的预约信息
     * @return 预约信息列表
     */
    @GetMapping("/select")
    public ResponseEntity<List<UserAppointmentInfo>> getAllAppointments(String userId) {
        List<UserAppointmentInfo> appointments = userAppointmentInfoService.getAllAppointments(userId);
        return ResponseEntity.ok(appointments); // 返回200状态码和预约信息列表
    }

    /**
     * 续约
     * @param appointmentId 预约ID
     * @param newEndTime 新的结束时间
     * @return 操作结果
     */
    @PutMapping("/renew")
    public ResponseEntity<String> renewAppointment(
            @RequestParam String appointmentId,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date newEndTime) {
        try {
            userAppointmentInfoService.renewAppointment(appointmentId, newEndTime);
            return ResponseEntity.ok("renew success"); // 返回200状态码，表示成功
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage()); // 返回400状态码，表示请求错误
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("预约续约失败"); // 返回500状态码，表示服务器错误
        }
    }

    /**
     * 手动更新预约状态
     * @param appointmentId 预约ID
     * @param newState 新的状态
     * @return 操作结果
     */
    @PutMapping("/updateAppointmentState")
    public ResponseEntity<String> manuallyUpdateAppointmentState(
            @RequestParam String appointmentId,
            @RequestParam int newState) {
        try {
            userAppointmentInfoService.manuallyUpdateAppointmentState(appointmentId, newState);
            return ResponseEntity.ok("Status update successful"); // 返回200状态码，表示成功
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage()); // 返回400状态码，表示请求错误
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("状态更新失败"); // 返回500状态码，表示服务器错误
        }
    }
}
